<template>
  <!-- 发布资讯页面 -->
  <div>
    <div class="publish_content">
      <el-form
        :model="publishForm"
        :rules="rules"
        ref="publish_form"
        label-width="80px"
      >
        <!-- 文章标题 -->
        <el-form-item label="标题" prop="title" style="width: 65%;">
          <el-input v-model="publishForm.title"></el-input>
        </el-form-item>
        <!-- 文章分类 -->
        <el-form-item label="分类" prop="categoryId">
          <!-- 栏目下拉框 -->
          <el-select
            v-model="publishForm.categoryId"
            clearable
            placeholder="请选择栏目"
          >
            <el-option
              v-for="category in categoryData"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="封皮">
          <el-upload
            v-model="publishForm.cover"
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="publishForm.cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span style="color:#ccc">文件大小不允许超过3M</span>
        </el-form-item>

        <!-- 正文 -->
        <el-form-item label="正文" prop="content">
          <tinymce v-model="publishForm.content" :height="280"></tinymce>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <el-button @click="$router.push({ path: 'List' })">返回</el-button>
      <el-button type="primary" @click="submitForm">发布</el-button>
    </div>
  </div>
</template>

<script>
import { get, post } from "@/utils/request";
import { mapGetters } from "vuex";
import Tinymce from "@/components/Tinymce";
// 引入文件上传和文件预览路径
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  components: { Tinymce },
  data() {
    return {
      // 上传文件的服务器地址
      uploadFileURL,
      // 图片的预览路径
      imageUrl: "",
      // 文章栏目类别
      categoryData: [],
      // 表单对象
      publishForm: {
        title: "",
        categoryId: "",
        content: "",
        // 封面
        cover: "",
        // 作者id
        authorId: "",
      },
      // 表单验证规则
      rules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
        categoryId: [{ required: true, message: '请选择栏目', trigger: 'blur' }],
      },
    };
  },
  computed: {
    // 使用辅助函数获取用户id
    ...mapGetters(["user"]),
  },
  methods: {
    // 获取所有文章的栏目类型
    async getAllCategoryData() {
      let res = await get("/category/findAll");
      this.categoryData = res.data;
    },
    // 上传成功之后调用的方法
    handleSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      // 上传成功之后 更新imageUrl
      this.publishForm.cover = showFileURL + res.data.id;
    },
    // 上传之前要做的一些限制
    beforeUpload(file) {
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传头像图片大小不能超过 3MB!");
      }
      // return  isLt3M;
    },
    // 表单提交
    submitForm() {
      console.log(this.publishForm);
      this.$refs["publish_form"].validate(async (valid) => {
        if (valid) {
          // 发送表单验证的请求 提交表单对象
          this.publishForm.authorId = this.user.id;
          let res = await post("/article/saveOrUpdate", this.publishForm);
          // 给用户一个成功的提示
          if (res.status == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            // 清空表单对象
            this.publishForm = {};
            this.$router.push({ path: "List" });
          } else {
            this.$message.error(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  created() {
    this.getAllCategoryData();
  },
  mounted() {},
};
</script>
<style scoped>
.footer {
  float: right;
}
</style>